package com.joizhang.seckill.utils;

import org.apache.commons.codec.digest.DigestUtils;

import java.util.Random;

public class MD5Util {

    private static final String SALT = "1a2b3c4d";

    private static final char[] SALT_CHARS = "abcdefghijklmnopqrstuvwxyz01234567890123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ~!@#$%^&*()_+{}:<>?`[];',./".toCharArray();

    public static String getSalt() {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 8; i++) {
            char ch = SALT_CHARS[new Random().nextInt(SALT_CHARS.length)];
            stringBuilder.append(ch);
        }
        return stringBuilder.toString();
    }

    public static String md5(String src) {
        return DigestUtils.md5Hex(src);
    }

    /**
     * 第一次MD5加密，用于网络传输
     *
     * @param password 密码
     * @return MD5
     */
    public static String inputPassToFormPass(String password) {
        //避免在网络传输被截取然后反推出密码，所以在md5加密前先打乱密码
        String str = "" + SALT.charAt(0) + SALT.charAt(2) + password + SALT.charAt(5) + SALT.charAt(4);
        return md5(str);
    }

    /**
     * 第二次MD5加密，用于存储到数据库
     *
     * @param password 密码
     * @param salt     盐
     * @return MD5
     */
    public static String formPassToDBPass(String password, String salt) {
        String str = password + salt;
        return md5(str);
    }

    /**
     * 合并
     *
     * @param password 密码
     * @param salt     盐
     * @return MD5
     */
    public static String inputPassToDbPass(String password, String salt) {
        String formPass = inputPassToFormPass(password);
        return formPassToDBPass(formPass, salt);
    }

}
